import mqtt from "mqtt";

export function useMqtt() {
  const connectUrl = `wss://s.aiying310.cn:443/mqtt`;
  const options = {
    connectTimeout: 30000, // ms
    reconnectPeriod: 4000, // ms
    clean: true,
    username: '',
    password: '',
  }
  let client = null;
  let connecting = false;
  let retryTimes = 0;
  let subscribeSuccess = false;
  const reviceData = ref(null);
  let currentTopic = ''

  function initData() {
    // client = {connected: false};
    client = null;
    connecting = false;
    retryTimes = 0;
    subscribeSuccess = false;
  }

  // 重连
  function handleOnReConnect() {
    retryTimes += 1;
    if (retryTimes > 5) {
      try {
        client.end();
        initData();
        console.log("Connection maxReconnectTimes limit, stop retry");
      } catch (error) {
        console.log(error.toString());
      }
    }
  }

  // 创建链接
  function createConnection(topic, token, onMessage){
    try {
      connecting = true;
      options.username = token;
      client = mqtt.connect(connectUrl, options);
      if(client.on) {
        client.on("connect", () => {
          connecting = false;
          const channel = currentTopic || topic;
          console.log("Connection succeeded!", channel);
          if (client && channel){
            doSubscribe(channel)
          }
        });
        client.on("error", (error) => {
          console.log("Connection failed", error);
        });
        client.on("reconnect", handleOnReConnect);
        client.on("message", (topic, message) => {
          var res = message.toString();
          if (res) {
            const data = JSON.parse(res);
            reviceData.value = data;
            onMessage(topic, data);
            // console.log(333, data);
            // console.log(`${topic}, Received message: ${data}`);
          }
        });
      }
    } catch (error) {
      connecting = false;
      console.log("mqtt.connect error", error);
    }
  }

  // 订阅
  function doSubscribe(topic, qos=0) {
    currentTopic = topic;
    client.subscribe(topic, { qos }, (error, res) => {
      if (error) {
        console.log('Subscribe to topics error', error)
        return
      }
      subscribeSuccess = true
      console.log('Subscribe to topics res', res)
    })
  }

  // 取消订阅
  function doUnSubscribe(topic) {
    client.unsubscribe(topic, error => {
      if (error) {
        console.log('Unsubscribe error', error)
      }
    })
  }

  // 更改订阅话题
  function reSubscrobe(topic){
    if (currentTopic) doUnSubscribe(currentTopic);
    doSubscribe(topic);
  }

  // 断开链接
  function destroyConnection() {
    try {
      client.end(false, () => {
        initData();
        client = null;
        console.log('Successfully disconnected!')
      })
    } catch (error) {
      console.log('Disconnect failed', error.toString())
    }
  }

  // 主动向服务器发布消息
  function doPublish(publish) {
    const { topic, qos, payload } = publish
    client.publish(topic, payload, { qos }, error => {
      if (error) {
        console.log('Publish error', error)
      }
    })
  }

  // onBeforeMount(() => {
  //   createConnection();
  // })

  // onBeforeUnmount(() => {
  //   destroyConnection();
  // })

  return {
    createConnection,
    destroyConnection,
    doSubscribe,
    doUnSubscribe,
    reSubscrobe,
    reviceData,
  };
}
